package com.elf.reactnative;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.modules.core.PermissionAwareActivity;
import com.facebook.react.modules.core.PermissionListener;

import java.io.File;

public class ReactActivity extends AppCompatActivity
        implements DefaultHardwareBackBtnHandler, PermissionAwareActivity {

    private final static String ARG_BUNDLE_INFO = "bundleInfo";
    private final static String ARG_EXTRAS = "extras";

    private ReactNativeDelegate mDelegate;

    private Bundle savedInstanceState;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rn_activity_react);
        this.savedInstanceState = savedInstanceState;

        ReactAppInfo reactAppInfo = getJsBundleInfo();
        if (reactAppInfo == null) {
            mDelegate = new ReactNativeDelegate(ReactActivity.this, "", "app");
            mDelegate.onCreate(savedInstanceState);
            setContentView(mDelegate.getRootView());
        } else {
            start(reactAppInfo);
        }
    }

    protected ReactAppInfo getJsBundleInfo() {
        String jsBundleInfo = getIntent().getStringExtra(ARG_BUNDLE_INFO);
        return JSON.parseObject(jsBundleInfo, ReactAppInfo.class);
    }

    protected void start(ReactAppInfo reactAppInfo) {
        String jsFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()
                + File.separator + reactAppInfo.id + "_" + reactAppInfo.version + ".bundle";

        mDelegate = new ReactNativeDelegate(ReactActivity.this, jsFile, reactAppInfo.mainComponentName);
        mDelegate.getReactNativeHost().getReactInstanceManager();

        FileDownload.download(reactAppInfo.url, jsFile, new FileDownload.DownloadListener() {
            @Override
            public void success(final String fileName) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mDelegate.onCreate(savedInstanceState);
                        setContentView(mDelegate.getRootView());
                    }
                });
            }

            @Override
            public void fail(final String msg) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showMsg(msg);
                    }
                });
            }
        });
    }

    private void showMsg(String msg) {
        findViewById(R.id.progress_bar).setVisibility(View.GONE);
        TextView tv_msg = findViewById(R.id.tv_msg);
        tv_msg.setVisibility(View.VISIBLE);
        tv_msg.setText(msg);
    }

    @Override
    public void invokeDefaultOnBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void requestPermissions(String[] permissions, int requestCode, PermissionListener listener) {
        mDelegate.requestPermissions(permissions, requestCode, listener);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        mDelegate.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    //----- 生命周期 通过ReactActivityDelegateImpl 传递

    @Override
    public void onNewIntent(Intent intent) {
        if (!mDelegate.onNewIntent(intent)) {
            super.onNewIntent(intent);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mDelegate.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mDelegate.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mDelegate.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        mDelegate.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        try {
            return mDelegate.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
        } catch (AssertionError e) {
            e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        try {
            return mDelegate.onKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
        } catch (AssertionError e) {
            e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
        try {
            return mDelegate.onKeyLongPress(keyCode, event) || super.onKeyLongPress(keyCode, event);
        } catch (AssertionError e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.onKeyLongPress(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        if (!mDelegate.onBackPressed()) {
            super.onBackPressed();
        }
    }

    //----- 生命周期 通过ReactActivityDelegateImpl 传递  end

    public static void open(Activity activity, String jsBundleInfo, String extras, int requestCode) {
        Intent intent = new Intent(activity, ReactActivity.class);
        intent.putExtra(ARG_BUNDLE_INFO, jsBundleInfo);
        if (!TextUtils.isEmpty(extras)) {
            intent.putExtra(ARG_EXTRAS, extras);
        }
        activity.startActivityForResult(intent, requestCode);
    }
}
